package com.ruoyi.danny.controller;

import com.ruoyi.danny.listener.BusinessException;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.ActivitiObjectNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

    // 处理所有Activiti相关异常
    @ExceptionHandler(ActivitiException.class)
    public ResponseEntity<ErrorResponse> handleActivitiException(ActivitiException e) {
        ErrorResponse error = new ErrorResponse();
        
        // 提取自定义异常
        Throwable original = e.getCause();
        if (original instanceof BusinessException) {
            BusinessException bizEx = (BusinessException) original;
            //error.setCode(bizEx.getErrorCode());
            error.setMessage(bizEx.getMessage());
            return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
        }
        
        // 处理内置异常
        if (e instanceof ActivitiObjectNotFoundException) {
            error.setCode("OBJECT_NOT_FOUND");
            error.setMessage("流程对象不存在：" + e.getMessage());
        } else {
            error.setCode("PROCESS_ERROR");
            error.setMessage("流程执行异常：" + e.getMessage());
        }
        
        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    // 异常响应实体

    public static class ErrorResponse {
        private String code;
        private String message;

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }
        // getters/setters
    }
}